package com.dormitory.dormitory_management.dao;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class SelectId {
    private SqlSessionFactory sqlSessionFactory;

    public SelectId(String configPath)throws IOException
    {
        InputStream inputStream = Resources.getResourceAsStream(configPath);
        sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
    }

    public boolean selectId(int idd){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int flag = sqlSession.selectOne("selectId",idd);
        sqlSession.commit();
        sqlSession.close();
        return flag<=0;   //如果没有该条记录则返回true表示进行新添宿舍信息

    }

    //flag：
    //      1：用户名不存在    2：密码不对  3: 学生   4：管理员
    public int login(String userid,String password){
        int flag=-1;
        String result="";
        Map<String,String> m1=new HashMap<>();
        m1.put("uid",userid);
        m1.put("password",password);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        result=sqlSession.selectOne("login1",userid);
        if(result==null)
        {
            sqlSession.commit();
            sqlSession.close();
            return 1;
        }
        else {
            result= sqlSession.selectOne("login2", m1);
            if(result==null)
            {
                sqlSession.commit();
                sqlSession.close();
                return 2;
            }


            else if(result.equals("1")){
                sqlSession.commit();
                sqlSession.close();
                return 4;
            }
            else if(result.equals("0")){
                sqlSession.commit();
                sqlSession.close();
                return 3;
            }
            else
                return 999;
        }
    }

    public int CountNum(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int num = sqlSession.selectOne("count");
        sqlSession.commit();
        sqlSession.close();
        return num;

    }
}
